<script setup>
import { ref, onMounted } from 'vue'
import { User } from '@vicons/fa'
import { MdLogOut } from '@vicons/ionicons4'
import { MoonOutline, SunnyOutline } from '@vicons/ionicons5'
import { useMainStore } from '../pinia.js'

const mainStore = useMainStore()

const emit = defineEmits(['message'])

const showLoginModal = ref(false)
const loginLoading = ref(false)

const username = ref('')
const password = ref('')

onMounted(async () => {
  console.log('HeaderBar onMounted - Restoring user state from localStorage')
  username.value = localStorage.getItem('username')
  
  const storedSgsToken = localStorage.getItem('sgsToken')
  const storedAuthToken = localStorage.getItem('authToken')
  const storedUserRole = localStorage.getItem('userRole') || 'user'
  const storedDisplayUsername = localStorage.getItem('displayUsername') || ''
  const storedUserInfo = localStorage.getItem('userInfo')
  
  console.log('Stored values:', {
    sgsToken: storedSgsToken,
    authToken: storedAuthToken,
    userRole: storedUserRole,
    displayUsername: storedDisplayUsername,
    userInfo: storedUserInfo
  })
  
  mainStore.sgsToken = storedSgsToken
  mainStore.authToken = storedAuthToken
  mainStore.userRole = storedUserRole
  mainStore.displayUsername = storedDisplayUsername
  mainStore.userInfo = storedUserInfo ? JSON.parse(storedUserInfo) : null
  
  console.log('MainStore state after restoration:', {
    userRole: mainStore.userRole,
    isAdmin: mainStore.isAdmin,
    canAccessAdminFeatures: mainStore.canAccessAdminFeatures
  })
  
  if (mainStore.sgsToken && mainStore.authToken) {
    try {
      const { success, userInfo } = await mainStore.checkAuth()
      if (success) {
        mainStore.displayUsername = userInfo.username
        localStorage.setItem('displayUsername', userInfo.username)
      } else {
        throw new Error('Token expired')
      }
    } catch {
      mainStore.sgsToken = ''
      mainStore.authToken = ''
      localStorage.removeItem('sgsToken')
      localStorage.removeItem('authToken')
      showLoginModal.value = true
    }
  } else {
    showLoginModal.value = true
  }
})

const handleLogin = async () => {
  loginLoading.value = true
  localStorage.setItem('username', username.value)
  const response = await fetch('/auth/login', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      username: username.value,
      password: password.value
    })
  })
  const responseData = await response.json()
  console.log('Login response data:', responseData)
  
  const { success, token, uname, sgsToken, info, role, userInfo } = responseData
  if (success) {
    console.log('Login successful, setting user info:', {
      token,
      uname,
      sgsToken,
      role,
      userInfo
    })
    
    // 使用setUserInfo方法设置完整的用户信息
    mainStore.setUserInfo({
      token,
      uname,
      sgsToken,
      role,
      userInfo
    })
    
    // 保存到localStorage
    localStorage.setItem('authToken', token)
    localStorage.setItem('sgsToken', sgsToken)
    localStorage.setItem('displayUsername', uname)
    localStorage.setItem('userRole', role || 'user')
    if (userInfo) {
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
    }
    
    console.log('MainStore state after login:', {
      userRole: mainStore.userRole,
      isAdmin: mainStore.isAdmin,
      canAccessAdminFeatures: mainStore.canAccessAdminFeatures
    })
    
    loginLoading.value = false
    showLoginModal.value = false
    emit('message', 'success', 'Login success')
  } else {
    loginLoading.value = false
    emit('message', 'warning', info)
  }
}

const isUserButtonHovered = ref(false)
const handleThemeToggle = () => {
  mainStore.toggleTheme()
}
const logout = () => {
  mainStore.clearUserInfo()
  localStorage.removeItem('sgsToken')
  localStorage.removeItem('authToken')
  localStorage.removeItem('userRole')
  localStorage.removeItem('displayUsername')
  localStorage.removeItem('userInfo')
  showLoginModal.value = true
  emit('message', 'success', 'Logout success')
}
</script>

<template>
  <div class="header-bar">
    <div class="header-background">
      <div class="header-content">
        <!-- 左侧标题区域 -->
        <div class="header-left">
          <div class="logo-section">
            <div class="logo-icon">
              <svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
                <rect width="32" height="32" rx="6" fill="url(#gradient)"/>
                <!-- 简约的文档图标 -->
                <rect x="6" y="8" width="14" height="16" rx="2" fill="white" opacity="0.95"/>
                <rect x="8" y="11" width="10" height="1.2" fill="#1890ff" opacity="0.6"/>
                <rect x="8" y="14" width="7" height="1.2" fill="#1890ff" opacity="0.6"/>
                <rect x="8" y="17" width="10" height="1.2" fill="#1890ff" opacity="0.6"/>
                <rect x="8" y="20" width="8" height="1.2" fill="#1890ff" opacity="0.6"/>
                <!-- 简约的转换箭头 -->
                <path d="M22 14l3 2-3 2" stroke="white" stroke-width="1.8" fill="none" opacity="0.9"/>
                <defs>
                  <linearGradient id="gradient" x1="0" y1="0" x2="32" y2="32" gradientUnits="userSpaceOnUse">
                    <stop stop-color="#1890ff"/>
                    <stop offset="1" stop-color="#40a9ff"/>
                  </linearGradient>
                </defs>
              </svg>
            </div>
            <div class="title-section">
              <h1 class="main-title">TRF to GPO</h1>
              <!-- <p class="sub-title">TRF导入GPO系统</p> -->
            </div>
          </div>
        </div>
        
        <!-- 右侧用户区域 -->
        <div class="header-right">
          <!-- 主题切换按钮 -->
          <div class="theme-toggle">
            <n-button
              quaternary
              circle
              size="medium"
              @click="handleThemeToggle"
              :title="mainStore.isDarkTheme ? '切换到浅色主题' : '切换到深色主题'"
              :class="{ 'theme-button-dark': mainStore.isDarkTheme }"
            >
              <template #icon>
                <n-icon size="18" :color="mainStore.isDarkTheme ? '#ffffff' : '#666666'">
                  <SunnyOutline v-if="mainStore.isDarkTheme" />
                  <MoonOutline v-else />
                </n-icon>
              </template>
            </n-button>
          </div>
          
          <div class="user-section">
            <div v-if="mainStore.displayUsername" class="user-info">
              <n-tooltip trigger="hover" placement="bottom-end">
                <template #trigger>
                  <div class="welcome-text">
                    <span class="greeting">欢迎回来</span>
                    <span class="username">{{ mainStore.displayUsername }}</span>
                  </div>
                </template>
                <div class="user-info-tooltip">
                  <div class="tooltip-title">My Account</div>
                  <div class="tooltip-content">
                    <div class="info-item">
                      <span class="info-label">Name: </span>
                      <span class="info-value">{{ mainStore.displayUsername }}</span>
                    </div>
                    <div class="info-item">
                      <span class="info-label">Role: </span>
                      <span class="info-value">{{ mainStore.userRoleDisplayName }}</span>
                    </div>
                    <div v-if="mainStore.userInfo?.labCode" class="info-item">
                      <span class="info-label">Lab Code: </span>
                      <span class="info-value">{{ mainStore.userInfo.labCode }}</span>
                    </div>
                    <div v-if="mainStore.userInfo && Object.keys(mainStore.userInfo).length > 0 && (mainStore.isRegularAdmin || mainStore.isSystemAdmin)" class="info-item">
                      <span class="info-label">完整信息:</span>
                      <pre class="info-json">{{ JSON.stringify(mainStore.userInfo, null, 2) }}</pre>
                    </div>
                  </div>
                </div>
              </n-tooltip>
              <div class="user-avatar" @click="logout" @mouseover="isUserButtonHovered = true" @mouseleave="isUserButtonHovered = false">
                <n-icon size="18" :color="isUserButtonHovered ? '#ff6b6b' : '#18a058'">
                  <MdLogOut v-if="isUserButtonHovered"/>
                  <User v-else/>
                </n-icon>
              </div>
            </div>
            <n-button
              v-else
              class="login-btn"
              type="primary"
              size="medium"
              @click="showLoginModal = true"
              :render-icon="() => User"
            >
              立即登录
            </n-button>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 登录模态框 -->
  <n-modal
    v-model:show="showLoginModal"
    :close-on-esc="false"
    :mask-closable="false"
    class="login-modal"
  >
    <n-card
      title="用户登录 (APAC账号)"
      :bordered="false"
      size="medium"
    >
      <n-alert type="info" style="margin-bottom: 16px;">
        请使用您的APAC域账号登录
      </n-alert>
      <n-form label-placement="left" label-width="auto">
        <n-form-item label="用户名">
          <n-input class="input-line" v-model:value="username" type="text" placeholder="apac\user_name" spellcheck="false"></n-input>
        </n-form-item>
        <n-form-item label="密码">
          <n-input class="input-line" v-model:value="password" type="password" show-password-on="click" @keyup.enter="handleLogin"></n-input>
        </n-form-item>
      </n-form>
      <template #footer>
        <n-space align="center" justify="center">
          <n-button @click="handleLogin" :loading="loginLoading" type="primary" secondary strong style="width: 16em;">登录</n-button>
        </n-space>
      </template>
    </n-card>
  </n-modal>
</template>

<style lang="stylus" scoped>
.header-bar
  position: fixed
  top: 0
  left: 0
  right: 0
  z-index: 1000
  height: 70px

.header-background
  height: 100%
  background: #ffffff
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06)
  border-bottom: 1px solid #e8e8e8
  transition: all 0.3s ease

// 深色主题下的头部背景
.dark .header-background
  background: #2d2d2d
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3)
  border-bottom: 1px solid #404040

.header-content
  height: 100%
  width: 100%
  padding: 0 24px
  display: flex
  justify-content: space-between
  align-items: center

.header-left
  display: flex
  align-items: center

.logo-section
  display: flex
  align-items: center
  gap: 12px

.logo-icon
  display: flex
  align-items: center
  justify-content: center
  transition: transform 0.3s ease

.logo-icon:hover
  transform: scale(1.05)

.title-section
  display: flex
  flex-direction: column
  gap: 2px

.main-title
  font-size: 24px
  font-weight: 600
  color: #333333
  margin: 0
  letter-spacing: 0.3px
  transition: color 0.3s ease

// 深色主题下的标题颜色
.dark .main-title
  color: #ffffff

.sub-title
  font-size: 13px
  color: #666666
  margin: 0
  font-weight: 400

.header-right
  display: flex
  align-items: center
  flex-shrink: 0
  margin-right: 50px
  gap: 12px

.theme-toggle
  display: flex
  align-items: center

// 深色主题下的主题切换按钮样式
.theme-button-dark
  background: rgba(255, 255, 255, 0.1) !important
  border: 1px solid rgba(255, 255, 255, 0.2) !important

.theme-button-dark:hover
  background: rgba(255, 255, 255, 0.2) !important
  border-color: rgba(255, 255, 255, 0.3) !important

.user-section
  display: flex
  align-items: center
  white-space: nowrap

.user-info
  display: flex
  align-items: center
  gap: 16px
  padding: 8px 16px
  background: rgba(255, 255, 255, 0.1)
  border-radius: 25px
  backdrop-filter: blur(10px)
  border: 1px solid rgba(255, 255, 255, 0.2)
  white-space: nowrap
  transition: all 0.3s ease

// 深色主题下的用户信息样式
.dark .user-info
  background: rgba(255, 255, 255, 0.05)
  border: 1px solid rgba(255, 255, 255, 0.1)

.welcome-text
  display: flex
  flex-direction: column
  align-items: flex-end
  gap: 2px

.greeting
  font-size: 12px
  color: #999999
  font-weight: 400
  transition: color 0.3s ease

// 深色主题下的问候语颜色
.dark .greeting
  color: #cccccc

.username
  font-size: 14px
  color: #333333
  font-weight: 500
  transition: color 0.3s ease

// 深色主题下的用户名颜色
.dark .username
  color: #ffffff

.user-avatar
  width: 36px
  height: 36px
  border-radius: 50%
  background: #f5f5f5
  display: flex
  align-items: center
  justify-content: center
  cursor: pointer
  transition: all 0.3s ease
  border: 1px solid #e0e0e0

// 深色主题下的用户头像样式
.dark .user-avatar
  background: #404040
  border: 1px solid #555555

.user-avatar:hover
  background: #e8f4fd
  border-color: #1890ff
  transform: scale(1.05)

// 深色主题下的用户头像悬停样式
.dark .user-avatar:hover
  background: #4a4a4a
  border-color: #40a9ff

// 用户信息工具提示样式
.user-info-tooltip
  max-width: 400px
  padding: 0

.tooltip-title
  font-size: 14px
  font-weight: 600
  color: #333
  margin-bottom: 12px
  padding-bottom: 8px
  border-bottom: 1px solid #e8e8e8

// 深色主题下的tooltip标题样式
.dark .tooltip-title
  color: #e8e8e8
  border-bottom-color: #444

.tooltip-content
  .info-item
    display: flex
    align-items: flex-start
    margin-bottom: 8px
    
    &:last-child
      margin-bottom: 0
    
    .info-label
      font-weight: 500
      color: #666
      min-width: 80px
      flex-shrink: 0
    
    .info-value
      color: #333
      word-break: break-all
    
    .info-json
      font-size: 11px
      color: #666
      background: #f5f5f5
      padding: 8px
      border-radius: 4px
      margin-top: 4px
      max-height: 200px
      overflow-y: auto
      white-space: pre-wrap
      word-break: break-all

// 深色主题下的tooltip内容样式
.dark .tooltip-content
  .info-item
    .info-label
      color: #aaa
    
    .info-value
      color: #e8e8e8
    
    .info-json
      color: #ccc
      background: #2a2a2a
      border: 1px solid #444

.login-btn
  background: #1890ff !important
  border: 1px solid #1890ff !important
  color: white !important
  font-weight: 500 !important
  border-radius: 6px !important
  padding: 8px 16px !important
  transition: all 0.3s ease !important
  white-space: nowrap
  flex-shrink: 0

.login-btn:hover
  background: #40a9ff !important
  border-color: #40a9ff !important
  transform: translateY(-1px) !important
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3) !important

.login-modal
  width: 27em
  .n-card__content
    padding-bottom: 0
    input
      font-size: 13px!important

/* 响应式设计 */
@media (max-width: 768px)
  .header-content
    padding: 0 16px
  
  .main-title
    font-size: 20px
  
  .sub-title
    font-size: 11px
  
  .user-info
    gap: 12px
    padding: 6px 12px
  
  .welcome-text
    display: none
  
  .login-btn
    padding: 0 16px !important
    font-size: 14px !important
</style>